package com.xuecheng.media.api;

import com.xuecheng.base.exception.XuChengException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author Mr.M
 * @version 1.0
 * @description 媒资文件管理接口
 * @date 2022/9/6 11:29
 */
@Api(value = "媒资文件管理接口", tags = "媒资文件管理接口")
@RestController
@Slf4j
public class MediaFilesController {


    @Autowired
    MediaFileService mediaFileService;


    @ApiOperation("媒资列表查询接口")
    @PostMapping("/files")
    public PageResult<MediaFiles> list(@Validated PageParams pageParams, @RequestBody QueryMediaParamsDto queryMediaParamsDto) {
        Long companyId = 1232141425L;
        return mediaFileService.queryMediaFiels(companyId, pageParams, queryMediaParamsDto);

    }
    @PostMapping(value = "/upload/coursefile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public UploadFileResultDto upLoadFile(@RequestPart("filedata")MultipartFile multipartFile) throws UnsupportedEncodingException {
        Long companyId = 1232141425L;
        // 创建文件请求参数
        UploadFileParamsDto uploadFileParamsDto = new UploadFileParamsDto();
        String name = new String(multipartFile.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8");
        uploadFileParamsDto.setFilename(name);
        uploadFileParamsDto.setFileSize(multipartFile.getSize());
        uploadFileParamsDto.setFileType("001001");
        // 创建一个临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile("minio", ".temp");
            // 复制数据到临时文件
            multipartFile.transferTo(tempFile);
        } catch (IOException e) {
            log.error("文件拷贝本地失败：{}",e.getMessage());
            XuChengException.cast("文件本地拷贝失败");
        }
        // 获取文件路径
        String localFilePath = tempFile.getAbsolutePath();
        UploadFileResultDto uploadFileResultDto = mediaFileService.uploadFile(companyId,uploadFileParamsDto,localFilePath);
        return uploadFileResultDto;
    }

}
